package com.caishi.lkx.user.login;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.caishi.lkx.user.dto.LoginDto;
import com.caishi.lkx.user.ienum.type.UserAccountType;
import com.caishi.lkx.user.model.LoginInfoModel;
import com.caishi.lkx.user.service.ILoginInfoService;
import com.caishi.lkx.user.service.IUserService;
import com.zzw.common.exception.BizException;
import com.zzw.common.exception.BizRuntimeException;
import com.caishi.lkx.user.UserResultCode;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author huangpeng
 * @Description //考研2扫码登录
 * @Date 2023/4/4 14:54
 **/
@Service("scanLoginService")
@Slf4j
public class ScanLoginServiceImpl implements LoginService {
    @Resource
    private ILoginInfoService userLoginService;
    @Resource
    private IUserService<?> userService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    private final String PREFIX = "kaoyan2_";

    @Override
    public LoginInfoModel loginBase(LoginDto loginDto, HttpServletRequest request, HttpServletResponse response) throws BizException {
        String credential = loginDto.getCredential();
        if (StrUtil.isBlank(credential)) {
            String nextIdStr = IdUtil.getSnowflakeNextIdStr();
            String certificate =this.PREFIX + nextIdStr;
            redisTemplate.opsForValue().set(certificate, "");
            redisTemplate.expire(certificate, 2, TimeUnit.MINUTES);
            return LoginInfoModel.builder().certificate(certificate).loginType(UserAccountType.scan).build();
        } else {
            var jsonObject = JSON.parseObject(Base64.decodeStr(credential));
            var loginInfo = jsonObject.toJavaObject(LoginInfoModel.class);
            String certificate = loginInfo.getCertificate();
            Boolean hasKey = redisTemplate.hasKey(certificate);
            if (Boolean.FALSE.equals(hasKey)) {
                throw new BizRuntimeException(UserResultCode.QRcodeExpire);
            }
            String userId = (String) redisTemplate.opsForValue().get(certificate);
            if (StrUtil.isNotBlank(userId)) {
                List<LoginInfoModel> loginInfoModels = userLoginService.selectUserLoginInfo(userId);
                return loginInfoModels.get(0);
            }
            return LoginInfoModel.builder().certificate(certificate).loginType(UserAccountType.scan).build();
        }

    }
}
